﻿var myDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

function ShowHideToDropDownType(sender) {

    var connectionTypeFound = false;

    if (typeof (listOfConnectionTypesToShow) != 'undefined' && typeof (oracleRowDataClientID) != 'undefined') {
        var connectionTypesToShow = listOfConnectionTypesToShow.split(',');
        for (var i = 0; i < connectionTypesToShow.length; i++) {

            var connectionTypeValues = connectionTypesToShow[i].split(':');

            if (connectionTypeValues[0] == sender.options[sender.selectedIndex].value) {

                if (connectionTypeValues[1] == "Normal") {
                    document.getElementById(controlToShowClientID).style.display = 'block';
                    document.getElementById(destFieldRowClientID).style.display = 'block';
                    document.getElementById(oracleRowDataClientID).style.display = 'none';
                }
                else if (connectionTypeValues[1] == "Oracle") {
                    document.getElementById(oracleRowDataClientID).style.display = 'block';
                    document.getElementById(destFieldRowClientID).style.display = 'none';
                    document.getElementById(controlToShowClientID).style.display = 'none';
                }
                connectionTypeFound = true;
                break;
            }
        }

        if (!connectionTypeFound) {
            document.getElementById(destFieldRowClientID).style.display = 'block';
            document.getElementById(controlToShowClientID).style.display = 'none';
            document.getElementById(oracleRowDataClientID).style.display = 'none';
        }
    }
}

function FillDropDownFirstTime(fieldName, values) {
    EnsureFieldDefinition(fieldName);
    fieldConnections[fieldName].values = values;
}

var fieldConnections = new Array();
function EnsureFieldDefinition(fieldDisp) {
    if (typeof (fieldConnections[fieldDisp]) == 'undefined')
        fieldConnections[fieldDisp] = new Object();

    if (typeof (fieldConnections[fieldDisp].subControls) == 'undefined')
        fieldConnections[fieldDisp].subFields = new Array();
}
function ClearOptions(OptionList) {

    // Always clear an option list from the last entry to the first
    for (x = OptionList.length; x >= 0; x--) {
        OptionList[x] = null;
    }
}


function AddToOptionList(OptionList, OptionValue, OptionText, SelectedValue) {
    // Add option to the bottom of the list
    OptionList[OptionList.length] = new Option(OptionText, OptionValue);

    if (OptionValue == SelectedValue)
        OptionList[OptionList.length - 1].selected = true;
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
}
function RegisterListFocusEvents() {
    var HandleOptDblClickOld = HandleOptDblClick;
    HandleOptDblClick = function () {
        HandleOptDblClickOld();
        EnsureChangeCall();
    }

    var HandleLoseFocusOld = HandleLoseFocus;
    HandleLoseFocus = function () {
        HandleLoseFocusOld();
        EnsureChangeCall();
    }
}
addLoadEvent(RegisterListFocusEvents);

function EnsureChangeCall() {
    var ctrl = event.srcElement;

    if (ctrl.id == '_Select')
        var ctrl = document.getElementById(ctrl.ctrl);

    LookupDropDownChanges(ctrl, ctrl.fieldName);
}

function InitializeFieldDefinition(currentRow, fieldType, fieldName, fieldDisp) {

    var editControl = null;
    if (fieldType == "Text" ||
        fieldType == "Number") {
        editControl = currentRow.childNodes[1].childNodes[1].firstChild;
    }

    if (fieldType == "Choice" ||
        fieldType == "Lookup") {
        editControl = currentRow.childNodes[1].childNodes[1].firstChild;

        if (editControl.tagName == 'SPAN')
            editControl = editControl.firstChild;
    }

    if (fieldType == "DateTime") {
        editControl = currentRow.childNodes[1].childNodes[1].childNodes[1].firstChild.firstChild.firstChild.childNodes[2];
    }

    if (editControl != null) {
        EnsureFieldDefinition(fieldDisp);
        fieldConnections[fieldDisp].name = fieldName;
        fieldConnections[fieldDisp].type = fieldType;
        fieldConnections[fieldDisp].disp = fieldDisp;
        fieldConnections[fieldDisp].ctrl = editControl;

        if (fieldType == "DateTime") {

            var functionDateCall = DateTimeSearchDay;

            var oldClickDay = OnPickerFinish;
            OnPickerFinish = function (resultfield) {
                functionDateCall(resultfield, fieldDisp);
                oldClickDay(resultfield);
            }

            editControl.onblur = functionDateCall;
            editControl.onchange = functionDateCall;
        }

        if (fieldType == "Lookup") {

            var functionCall = function () {
                LookupDropDownChanges(this, fieldDisp);
            };

            editControl.fieldName = fieldDisp;
            if (editControl.onchange == null)
                editControl.onchange = functionCall;
            else
                editControl.onchange += functionCall;

            var refreshImage = document.createElement('img');
            refreshImage.src = "/_layouts/images/recurrence.gif";
            refreshImage.style.cursor = "pointer";
            refreshImage.style.marginRight = "3px";
            refreshImage.style.display = fieldConnections[fieldDisp].subFields.length == 0 ? "none" : "block";
            refreshImage.onclick = functionCall;
            fieldConnections[fieldDisp].imageControl = refreshImage;

            var parentSpan = editControl.parentNode;
            parentSpan.style.float = 'right';
            parentSpan.parentNode.style.verticalAlign = 'middle';

            if (!parentSpan.nextSibling)
                parentSpan.parentNode.appendChild(refreshImage);
            else
                parentSpan.parentNode.insertBefore(refreshImage, parentSpan.nextSibling);

            // Enforce style changes
            parentSpan.style.cssText = parentSpan.style.cssText;
        }

        if (fieldType == 'Text' && typeof (fieldConnections[fieldDisp].values) != 'undefined') {

            var functionCall = function () {
                LookupDropDownChanges(this, fieldDisp);
            };

            // Create drop down control
            var hidTextBox = editControl;
            var newDropDown = document.createElement("select");
            newDropDown.id = hidTextBox.id + "_DropDown";
            newDropDown.textbox = hidTextBox.id;
            hidTextBox.style.display = 'none';
            hidTextBox.dropdown = newDropDown.id;
            editControl = newDropDown;

            var textFieldValue = hidTextBox.value;

            if (editControl.onchange == null)
                editControl.onchange = functionCall;
            else
                editControl.onchange += functionCall;

            var allValues = fieldConnections[fieldDisp].values.split(',');
            ClearOptions(editControl);
            AddToOptionList(editControl, "", "", "");
            for (var i = 0; i < allValues.length; i++)
                AddToOptionList(editControl, allValues[i], allValues[i], textFieldValue);

            hidTextBox.parentNode.insertBefore(newDropDown, hidTextBox);
        }
    }
}

var parentListID = "";
var parentWebUrl = "";
function EnsureSubField(parentField, childField) {

    // Ensure parent definition is set, and add current field as child
    EnsureFieldDefinition(parentField);
    fieldConnections[parentField].subFields[fieldConnections[parentField].subFields.length] = childField;

    // If imageControl is defined on lookup, show it
    if (typeof (fieldConnections[parentField].imageControl) != 'undefined')
        fieldConnections[parentField].imageControl.style.display = 'block';
}
function EnsureFormParameters(listID, webUrl) {
    parentListID = listID;
    parentWebUrl = webUrl;
}

function PopulateUserFields(parentField, itemID) {

    if (fieldConnections[parentField].subFields.length == 0)
        return;

    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    var urlLocation = parentWebUrl + "/_layouts/ManageFieldAssociations/GetListData.aspx?List=" + escape(parentListID) +
                                        "&PF=" + escape(parentField) + "&ID=" + escape(itemID);
    xmlDoc.load(urlLocation);
    var docEl = xmlDoc.documentElement;

    if (docEl == null)
        return;

    for (var i = 0; i < docEl.childNodes.length; i++) {
        var fieldName = docEl.childNodes[i].getAttribute("FieldName");
        var value = docEl.childNodes[i].getAttribute("Value");

        if (typeof (fieldConnections[fieldName]) != 'undefined')
            if (fieldConnections[fieldName].type == 'Text' ||
                fieldConnections[fieldName].type == 'Number')
                if (fieldConnections[fieldName].ctrl.innerText == '')
                    fieldConnections[fieldName].ctrl.innerText = value;
    }
}

function LookupDropDownChanges(sender, fieldName) {
    var lookupControl = sender;

    if (sender.tagName == 'IMG')
        lookupControl = sender.previousSibling.firstChild;

    if (sender.tagName == 'SPAN')
        lookupControl = lookupControl.firstChild;

    var fieldValue;
    if (typeof (lookupControl.options) != 'undefined')
        fieldValue = lookupControl.options[lookupControl.selectedIndex].value;
    else
        fieldValue = lookupControl.value;

    if (fieldValue != null && fieldValue != "") {

        if (typeof (lookupControl.textbox) != 'undefined')
            document.getElementById(lookupControl.textbox).value = fieldValue;

        PopulateUserFields(fieldName, fieldValue);
    }
}

// Setting the day of the week in the destination selection box
// selection box should have values: ['', "Sun', ..., 'Sat']
function DateTimeSearchDay(result, fieldDisp) {

    if (typeof (fieldDisp) == 'undefined')
        return;

    var stringDate;
    if (typeof (result) == 'undefined')
        stringDate = fieldConnections[fieldDisp].ctrl.innerText;
    else
        stringDate = result.value;

    var dateParts = stringDate.split("/");
    var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
    var dayIndex = date.getDay();

    if (dayIndex >= 0)
        for (var i = 0; i < fieldConnections[fieldDisp].subFields.length; i++) {
            var subFieldName = fieldConnections[fieldDisp].subFields[i];
            fieldConnections[subFieldName].ctrl.selectedIndex = dayIndex + 1;
        }
}